/*
 * Copyright (c) 2025 李伟国
 * SQL-API is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.moyu.sql.business.controller;

import com.moyu.sql.business.entity.MoyuSql;
import com.moyu.sql.business.service.IMoyuSqlService;
import com.moyu.sql.core.engine.MoyuSqlSession;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/moyu/sql")
public class MoyuSqlController {

    @Resource
    private IMoyuSqlService moyuSqlService;

    @Resource
    private MoyuSqlSession moyuSqlSession;

    /**
     * 获取分组下的sql列表
     *
     * @return sql列表
     */
    @GetMapping("list/{sqlGroupId}")
    public List<MoyuSql> list(@PathVariable String sqlGroupId) {
        return moyuSqlService.lambdaQuery().eq(MoyuSql::getSqlGroupId, sqlGroupId).list();
    }

    /**
     * 获取SQL详情
     *
     * @return 详情
     */
    @GetMapping("/{id}")
    public MoyuSql detail(@PathVariable String id) {
        return moyuSqlService.getById(id);
    }

    /**
     * 新增或更新
     *
     * @param moyuSql 数据
     * @return 数据
     */
    @PostMapping("")
    public MoyuSql save(@RequestBody MoyuSql moyuSql) {
        moyuSqlService.saveOrUpdate(moyuSql);
        moyuSqlSession.updateMappedStatement(moyuSql.getSqlId(), moyuSql.getSqlTemplate(), moyuSql.getSqlCommandType());
        return moyuSql;
    }

    /**
     * 删除
     *
     * @param id 主键
     * @return 是否成功
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable String id) {
        return moyuSqlService.removeById(id);
    }
}
